package com.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.demo.model.User;
import com.demo.result.Result;
import com.demo.service.UserService;
import com.demo.utils.DateUtils;
import com.demo.utils.JwtUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Tag( name = "用户接口",description = "用户接口")
public class UserController {
    @Autowired
    private UserService userService;
    @Resource
    private JwtUtils jwtUtils;
    @PostMapping("/login")
    @Operation(summary = "用户登录",description = "用户通过用户名，密码登录,并且返回响应结果信息")
    public Result loginNew(@RequestBody User userData) {
        // 从数据库查询用户
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", userData.getUsername());
        wrapper.eq("password", userData.getPassword());
        User user = userService.getOne(wrapper);
        if (user == null) {
            return Result.error("用户不存在");
        };
        if (user != null) {
            // 生成 JWT
            String token = jwtUtils.generateToken(user.getUsername());

            // 返回用户信息和 Token
            Map<String, Object> data = new HashMap<>();
            data.put("user", user);
            data.put("token", token);
            return Result.success(data);
        } else {
            return Result.error("用户名或密码错误");
        }
    }
    @PostMapping(value = "/registerNew")
    @Operation(summary = "用户注册",description = "用户注册")
    public Result register(@RequestBody User user) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", user.getUsername());
        User byId = userService.getOne(wrapper);
        if (byId!=null){
            return Result.error("用户已存在");
        }
        user.setIsLeader(0);
        user.setCreateTime(DateUtils.now());
        user.setUpdateTime(DateUtils.now());
        //直接插入
        boolean save = userService.save(user);
        if (save){
            return Result.success();
        }else {
            return Result.error();
        }
    }
    @GetMapping(value = "/exitLogin")
    @Operation(summary = "用户退出登录",description = "用户退出登录")
    public Result exitLogin() {
        return Result.success();
    }
    @GetMapping(value = "/getUser")
    @Operation(summary = "查询用户列表",description = "查询用户列表")
    public Result getUser(@RequestParam(value = "username",required = false) String username ) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        if (username != null) {
            wrapper.like("username", username);
        }
        wrapper.orderByDesc("createTime");
        List<User> userData = userService.getBaseMapper().selectList(wrapper);
        return Result.success(userData);
    }

    @PostMapping(value = "/updateUser")
    @Operation(summary = "修改用户",description = "修改用户")
    public Result updateUser(@RequestBody User user) {
        user.setUpdateTime(DateUtils.now());
        boolean b = userService.updateById(user);
        if (b){
            return Result.success();
        }else {
            return Result.error();
        }

    }
    @GetMapping(value = "/deleteUser")
    @Operation(summary = "用户删除",description = "用户删除")
    public Result deleteUser(@RequestParam(value = "id",required = false) String id ) {
        boolean b1 = userService.removeById(id);
        if (b1){
            return Result.success();
        }else {
            return Result.error();
        }
    }
    @PostMapping(value = "/addUserByAdmin")
    @Operation(summary = "添加用户通过管理员",description = "添加用户通过管理员")
    public Result addUserByAdmin(@RequestBody User user) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", user.getUsername());
        User byId = userService.getOne(wrapper);
        if (byId!=null){
            return Result.error("用户已存在");
        }
        user.setCreateTime(DateUtils.now());
        user.setUpdateTime(DateUtils.now());
        boolean b = userService.save(user);
        if (b){
            return Result.success();
        }else {
            return Result.error();
        }
    }

    @PostMapping("/resetPassword")
    public Result resetPassword(@RequestParam String username) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        if (userService.getOne(wrapper) == null) {
            return Result.error("邮箱不存在");
        }
        if (!jwtUtils.validateToken(username)) {
            return Result.error("token已过期");
        }
        if (!jwtUtils.getUsernameFromToken(username).equals(username)) {
            return Result.error("token无效");
        }
        User user = userService.getOne(wrapper);
        if (user == null) {
            return Result.error("邮箱不存在");
        }
        // 设置为默认密码（记得加密后再存入数据库）
        user.setPassword("123456");
        userService.updateById(user);
        return Result.success("密码重置成功");
    }

}
